/*
   给定一个数组和一个目标值，在数组中找到目标值的开始位置和结束位置。
 */

package com.diudiu.BinarySearch;

import java.util.Arrays;

public class Test03 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 5, 5, 6, 7, 8};
        int target = 5;
        // 调用开始位置的方法
        int form = fandFrom(arr, target);
        if (form == -1) {
            System.out.println("数组中不存在目标值");
        } else {
            int end = fandEnd(arr, target);
            System.out.println(Arrays.toString(new int[]{form, end}));
        }

    }

    private static int fandFrom(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) >>> 1;
            if (arr[mid] >= target) {
                // 目标值在mid的左边
                right = mid - 1;
            } else {
                // 目标值在mid的右边
                left = mid + 1;
            }
        }
        return left;
    }


    private static int fandEnd(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) >>> 1;
            if (arr[mid] <= target) {
                // 目标值在mid的左边
                left = mid + 1;
            } else {
                // 目标值在mid的右边
                right = mid - 1;
            }
        }
        return right;
    }
}